<template>
  <div class="color-analysis">
    <!-- 颜色分布概览 -->
    <el-card class="color-overview" v-loading="loading">
      <template #header>
        <span>颜色分布概览</span>
      </template>

      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ analysisData.totalColors || 0 }}</div>
            <div class="stat-label">总颜色数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ topColor?.color || '-' }}</div>
            <div class="stat-label">最常用颜色</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ topColor?.percentage || 0 }}%</div>
            <div class="stat-label">使用占比</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ topColor?.preferenceScore || 0 }}</div>
            <div class="stat-label">偏好指数</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 颜色偏好排行 -->
    <el-card class="color-ranking" v-loading="loading">
      <template #header>
        <span>颜色偏好排行</span>
      </template>

      <div class="color-list">
        <div 
          v-for="(color, index) in analysisData.topPreferredColors" 
          :key="color.color"
          class="color-item"
        >
          <div class="color-rank">{{ index + 1 }}</div>
          
          <div class="color-preview">
            <div 
              class="color-swatch" 
              :style="{ backgroundColor: color.colorHex || getColorHex(color.color) }"
            ></div>
          </div>
          
          <div class="color-info">
            <h4>{{ color.color }}</h4>
            <p>拥有 {{ color.count }} 件 · 穿着 {{ color.wearCount }} 次</p>
          </div>
          
          <div class="color-stats">
            <div class="percentage">{{ color.percentage }}%</div>
            <div class="preference-score">偏好: {{ color.preferenceScore }}</div>
          </div>
          
          <div class="color-bar">
            <el-progress 
              :percentage="parseFloat(color.percentage)" 
              :show-text="false"
              :stroke-width="8"
              :color="color.colorHex || getColorHex(color.color)"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 颜色搭配分析 -->
    <el-card class="color-combinations" v-loading="loading">
      <template #header>
        <span>常用颜色搭配</span>
      </template>

      <div class="combinations-grid">
        <div 
          v-for="combo in analysisData.colorCombinations" 
          :key="combo.colors.join('-')"
          class="combination-item"
        >
          <div class="combination-colors">
            <div 
              v-for="color in combo.colors" 
              :key="color"
              class="combo-color"
              :style="{ backgroundColor: getColorHex(color) }"
              :title="color"
            ></div>
          </div>
          
          <div class="combination-info">
            <div class="combo-frequency">{{ combo.frequency }} 次</div>
            <div class="combo-rating">
              <el-rate 
                v-model="combo.rating" 
                disabled 
                show-score 
                text-color="#ff9900"
                score-template="{value}"
              />
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 颜色建议 -->
    <el-card class="color-recommendations" v-loading="loading">
      <template #header>
        <span>颜色建议</span>
      </template>

      <div class="recommendations-list">
        <div 
          v-for="recommendation in analysisData.recommendations" 
          :key="recommendation.color"
          class="recommendation-item"
        >
          <div class="recommendation-icon">
            <el-icon v-if="recommendation.type === 'missing_basic'"><Plus /></el-icon>
            <el-icon v-else><Brush /></el-icon>
          </div>
          
          <div class="recommendation-content">
            <h4>{{ getRecommendationTitle(recommendation) }}</h4>
            <p>{{ recommendation.reason }}</p>
          </div>
          
          <div class="recommendation-color">
            <div 
              class="color-swatch" 
              :style="{ backgroundColor: getColorHex(recommendation.color) }"
            ></div>
            <span>{{ recommendation.color }}</span>
          </div>
        </div>
      </div>

      <div v-if="analysisData.recommendations?.length === 0" class="no-recommendations">
        <el-empty description="您的颜色搭配很均衡，暂无特别建议" />
      </div>
    </el-card>

    <!-- 颜色趋势图表 -->
    <el-card class="color-trends" v-loading="loading">
      <template #header>
        <span>颜色使用趋势</span>
      </template>

      <div class="chart-container">
        <div class="chart-placeholder">
          <el-empty description="图表功能开发中" />
          <p class="chart-note">
            这里将显示您在不同季节和时间段的颜色使用趋势图表
          </p>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { analysisAPI } from '@/api'

// 响应式数据
const loading = ref(false)
const analysisData = reactive({
  totalColors: 0,
  colorDistribution: [],
  topPreferredColors: [],
  leastPreferredColors: [],
  colorCombinations: [],
  recommendations: []
})

// 计算属性
const topColor = computed(() => {
  return analysisData.topPreferredColors?.[0] || null
})

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const response = await analysisAPI.getColorPreference()
    
    if (response.code === 200) {
      Object.assign(analysisData, response.data)
    } else {
      throw new Error(response.message || '获取颜色分析数据失败')
    }
  } catch (error) {
    console.error('获取颜色分析失败:', error)
    ElMessage.error('获取数据失败')
    
    // 使用模拟数据
    Object.assign(analysisData, {
      totalColors: 12,
      topPreferredColors: [
        { color: '黑色', count: 15, wearCount: 45, percentage: '25.0', preferenceScore: '3.0', colorHex: '#000000' },
        { color: '白色', count: 12, wearCount: 36, percentage: '20.0', preferenceScore: '3.0', colorHex: '#FFFFFF' },
        { color: '蓝色', count: 8, wearCount: 20, percentage: '13.3', preferenceScore: '2.5', colorHex: '#0066CC' },
        { color: '灰色', count: 6, wearCount: 15, percentage: '10.0', preferenceScore: '2.5', colorHex: '#808080' },
        { color: '红色', count: 4, wearCount: 8, percentage: '6.7', preferenceScore: '2.0', colorHex: '#FF0000' }
      ],
      colorCombinations: [
        { colors: ['黑色', '白色'], frequency: 15, rating: 4.5 },
        { colors: ['蓝色', '白色'], frequency: 12, rating: 4.2 },
        { colors: ['灰色', '黑色'], frequency: 8, rating: 4.0 }
      ],
      recommendations: [
        { type: 'missing_basic', color: '米色', reason: '建议添加米色单品，这是百搭的基础色' },
        { type: 'diversify', color: '绿色', reason: '尝试绿色系单品，增加颜色多样性' }
      ]
    })
  } finally {
    loading.value = false
  }
}

// 获取颜色十六进制值
const getColorHex = (colorName) => {
  const colorMap = {
    '黑色': '#000000',
    '白色': '#FFFFFF',
    '灰色': '#808080',
    '红色': '#FF0000',
    '蓝色': '#0066CC',
    '绿色': '#00CC66',
    '黄色': '#FFCC00',
    '紫色': '#9966CC',
    '粉色': '#FF99CC',
    '棕色': '#996633',
    '橙色': '#FF6600',
    '米色': '#F5F5DC'
  }
  return colorMap[colorName] || '#CCCCCC'
}

// 获取建议标题
const getRecommendationTitle = (recommendation) => {
  const titles = {
    missing_basic: `缺少基础色：${recommendation.color}`,
    diversify: `增加多样性：${recommendation.color}`,
    seasonal: `季节推荐：${recommendation.color}`
  }
  return titles[recommendation.type] || `颜色建议：${recommendation.color}`
}

// 页面初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.color-analysis {
  space-y: 20px;
}

.color-overview,
.color-ranking,
.color-combinations,
.color-recommendations,
.color-trends {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  border-radius: 8px;
  background: #f8f9fa;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.color-list {
  space-y: 16px;
}

.color-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 12px;
}

.color-rank {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 16px;
}

.color-preview {
  margin-right: 16px;
}

.color-swatch {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  border: 2px solid #eee;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.color-info {
  flex: 1;
  margin-right: 16px;
}

.color-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #333;
}

.color-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.color-stats {
  text-align: center;
  margin-right: 16px;
  min-width: 80px;
}

.percentage {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.preference-score {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.color-bar {
  width: 100px;
}

.combinations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.combination-item {
  padding: 16px;
  border: 1px solid #eee;
  border-radius: 8px;
  text-align: center;
}

.combination-colors {
  display: flex;
  justify-content: center;
  gap: 4px;
  margin-bottom: 12px;
}

.combo-color {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  border: 2px solid #eee;
}

.combination-info {
  space-y: 8px;
}

.combo-frequency {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.recommendations-list {
  space-y: 12px;
}

.recommendation-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 12px;
}

.recommendation-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #67C23A;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.recommendation-content {
  flex: 1;
  margin-right: 16px;
}

.recommendation-content h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #333;
}

.recommendation-content p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.recommendation-color {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.recommendation-color span {
  font-size: 12px;
  color: #666;
}

.no-recommendations {
  text-align: center;
  padding: 40px 20px;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
}

.chart-note {
  margin-top: 16px;
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .color-item {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .color-rank {
    margin-right: 0;
  }
  
  .color-info {
    margin-right: 0;
  }
  
  .color-stats {
    margin-right: 0;
  }
  
  .color-bar {
    width: 100%;
  }
  
  .combinations-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  
  .recommendation-item {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .recommendation-icon {
    margin-right: 0;
  }
  
  .recommendation-content {
    margin-right: 0;
  }
}
</style>
